﻿using AutoMapper;
using B.S.BasicData.Domain.Entities;
using B.S.BasicData.Error;
using B.S.BasicData.Infrastructure.InProfaces;
using B.S.BasicData.Read.Api.Application.Command.ProductsCommand;
using B.S.BasicData.Read.Api.DTO;
using MediatR;

namespace B.S.BasicData.Read.Api.Application.CommandHander.ProductsCommandHander
{
    public class ProductsFanCommandHander : IRequestHandler<ProductsFanCommand, ApiResult<List<ProductsDTO>>>
    {
        private readonly IMapper mapper;
        private readonly IBaseRepository<Products> ProductsRepository;
        private readonly IBaseRepository<Shop> ShopRepository;

        public ProductsFanCommandHander(IMapper mapper, IBaseRepository<Products> productsRepository, IBaseRepository<Shop> shopRepository)
        {
            this.mapper = mapper;
            ProductsRepository = productsRepository;
            ShopRepository = shopRepository;
        }

        public Task<ApiResult<List<ProductsDTO>>> Handle(ProductsFanCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<ProductsDTO>> result = new ApiResult<List<ProductsDTO>>();

            result.Code = ApiEnum.success;
            result.Msg = "查询成功";

            var list = from a in ProductsRepository.GetAll()
                       join b in ShopRepository.GetAll() on a.ShopId equals b.ShopId
                       where a.ProductsId == request.ProductsId && a.IsDel == false
                       select new ProductsDTO
                       {
                           ProductsId = a.ProductsId,
                           ShopId = a.ShopId,
                           ShopName = b.ShopName,
                           ProductionBatch = a.ProductionBatch,
                           ShelfLife = a.ShelfLife,
                           LicenseNumber = a.LicenseNumber,
                           Manufacturers = a.Manufacturers,
                           CoverImage = a.CoverImage,
                           CreateName = a.CreateName,
                           CreateTime = a.CreateTime,
                           UpdateName = a.UpdateName,
                           UpdateTime = a.UpdateTime,
                           IsDel = a.IsDel,
                       };
            var model = mapper.Map<List<ProductsDTO>>(list.ToList());
            result.Data = model;
            return Task.FromResult(result);
        }
    }
}
